import { ref, onMounted, onUnmounted, computed } from 'vue'
import { teamSocketManager } from '@/utils/teamSocketManager'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'

/**
 * 团队协作Socket.IO组合式函数
 */
export function useTeamSocket() {
  const authStore = useAuthStore()
  
  // 响应式状态
  const isConnected = ref(false)
  const connectionState = ref(teamSocketManager.ConnectionState.DISCONNECTED)
  const reconnectAttempts = ref(0)
  const currentTeamId = ref<number | null>(null)
  
  // 团队消息相关
  const teamMessages = ref<any[]>([])
  const onlineMembers = ref<any[]>([])
  
  // 连接状态计算属性
  const connectionStatus = computed(() => {
    switch (connectionState.value) {
      case teamSocketManager.ConnectionState.CONNECTED:
        return { text: '已连接', color: 'success', icon: 'success' }
      case teamSocketManager.ConnectionState.CONNECTING:
        return { text: '连接中...', color: 'warning', icon: 'loading' }
      case teamSocketManager.ConnectionState.RECONNECTING:
        return { text: `重连中(${reconnectAttempts.value})...`, color: 'warning', icon: 'loading' }
      case teamSocketManager.ConnectionState.FAILED:
        return { text: '连接失败', color: 'danger', icon: 'error' }
      default:
        return { text: '未连接', color: 'info', icon: 'info' }
    }
  })

  /**
   * 初始化团队Socket连接
   */
  const initTeamSocket = async () => {
    if (!authStore.isAuthenticated) {
      console.warn('⚠️ 用户未登录，跳过团队Socket初始化')
      return
    }

    try {
      const userId = authStore.user?.id
      if (!userId) {
        throw new Error('无法获取用户ID')
      }

      await teamSocketManager.connect(userId)
      console.log('✅ 团队Socket初始化成功')
      
    } catch (error) {
      console.error('❌ 团队Socket初始化失败:', error)
      ElMessage.error('团队协作连接失败，请刷新页面重试')
    }
  }

  /**
   * 断开团队Socket连接
   */
  const disconnectTeamSocket = () => {
    teamSocketManager.disconnect()
    isConnected.value = false
    connectionState.value = teamSocketManager.ConnectionState.DISCONNECTED
    currentTeamId.value = null
    teamMessages.value = []
    onlineMembers.value = []
    console.log('🔌 团队Socket连接已断开')
  }

  /**
   * 加入团队
   */
  const joinTeam = (teamId: number) => {
    if (!teamSocketManager.isConnected()) {
      ElMessage.warning('团队协作连接未建立，请稍后重试')
      return
    }

    currentTeamId.value = teamId
    teamSocketManager.joinTeam(teamId)
    
    // 获取团队在线成员
    setTimeout(() => {
      teamSocketManager.getTeamOnlineMembers(teamId)
    }, 500)
  }

  /**
   * 离开团队
   */
  const leaveTeam = (teamId: number) => {
    if (!teamSocketManager.isConnected()) {
      return
    }

    teamSocketManager.leaveTeam(teamId)
    
    if (currentTeamId.value === teamId) {
      currentTeamId.value = null
      teamMessages.value = []
      onlineMembers.value = []
    }
  }

  /**
   * 发送团队消息
   */
  const sendTeamMessage = (teamId: number, content: string, messageType: string = 'text') => {
    if (!teamSocketManager.isConnected()) {
      ElMessage.warning('团队协作连接未建立，无法发送消息')
      return false
    }

    if (!content.trim()) {
      ElMessage.warning('消息内容不能为空')
      return false
    }

    teamSocketManager.sendTeamMessage(teamId, content, messageType)
    return true
  }

  /**
   * 获取团队在线成员
   */
  const getTeamOnlineMembers = (teamId: number) => {
    if (!teamSocketManager.isConnected()) {
      return
    }

    teamSocketManager.getTeamOnlineMembers(teamId)
  }

  /**
   * 设置事件监听器
   */
  const setupEventListeners = () => {
    // 连接状态变化
    teamSocketManager.onConnectionStateChange('useTeamSocket', (state: string, attempts: number) => {
      connectionState.value = state
      reconnectAttempts.value = attempts
      isConnected.value = state === teamSocketManager.ConnectionState.CONNECTED
    })

    // 新团队消息 - 已由teamChatStore统一处理，这里不再重复监听

    // 团队在线成员
    teamSocketManager.on('team_online_members', (data: any) => {
      onlineMembers.value = data.members || []
    })

    // 成员在线状态变更
    teamSocketManager.on('member_online_status', (data: any) => {
      const memberIndex = onlineMembers.value.findIndex(member => member.userId === data.userId)
      
      if (data.isOnline) {
        // 用户上线
        if (memberIndex === -1) {
          // 获取最新的在线成员列表
          if (currentTeamId.value) {
            getTeamOnlineMembers(currentTeamId.value)
          }
        }
      } else {
        // 用户下线
        if (memberIndex > -1) {
          onlineMembers.value.splice(memberIndex, 1)
        }
      }
    })

    // 成员加入团队
    teamSocketManager.on('member_joined_team', (data: any) => {
      console.log('👋 成员加入团队:', data)
      // 可以在这里添加UI提示
    })

    // 成员离开团队
    teamSocketManager.on('member_left_team', (data: any) => {
      console.log('👋 成员离开团队:', data)
      // 可以在这里添加UI提示
    })

    // 加入团队成功
    teamSocketManager.on('joined_team', (data: any) => {
      console.log('✅ 成功加入团队:', data)
      ElMessage.success('已加入团队协作')
    })

    // 错误处理
    teamSocketManager.on('error', (error: any) => {
      console.error('❌ 团队Socket错误:', error)
      ElMessage.error(error.message || '团队协作出现错误')
    })
  }

  /**
   * 清理事件监听器
   */
  const cleanupEventListeners = () => {
    teamSocketManager.offConnectionStateChange('useTeamSocket')
    // new_team_message 已由teamChatStore统一处理，这里不再清理
    teamSocketManager.off('team_online_members')
    teamSocketManager.off('member_online_status')
    teamSocketManager.off('member_joined_team')
    teamSocketManager.off('member_left_team')
    teamSocketManager.off('joined_team')
    teamSocketManager.off('error')
  }

  // 组件挂载时初始化
  onMounted(() => {
    setupEventListeners()
    
    // 如果用户已登录，自动初始化连接
    if (authStore.isAuthenticated) {
      initTeamSocket()
    }
  })

  // 组件卸载时清理
  onUnmounted(() => {
    cleanupEventListeners()
  })

  return {
    // 状态
    isConnected,
    connectionState,
    connectionStatus,
    reconnectAttempts,
    currentTeamId,
    teamMessages,
    onlineMembers,
    
    // 方法
    initTeamSocket,
    disconnectTeamSocket,
    joinTeam,
    leaveTeam,
    sendTeamMessage,
    getTeamOnlineMembers
  }
}
